from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from .models import *
import time
from .WechatAction import WechatAction
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
from utils.WorkWechat import WorkWachat
from quanquaner.views import views as quaner
from utils.utils import *

@csrf_exempt
def wechat_main(request):
    wechat = WechatAction()
    if request.method == 'GET':
        if wechat.auth(settings.WECHAT_KEY['token'], request):
            return HttpResponse(request.GET['echostr'])
        else:
            return HttpResponse('')
    else:
        wechat.start(request)
        MsgType = wechat.data['MsgType'].strip()
        if MsgType == 'text':
            baidu = quaner.baiduWechatShow(request, wechat.data['Content'])
            if baidu:
                return HttpResponse(wechat.replayNews(baidu))
            else:
                return HttpResponse(wechat.replayText(wechat.data['Content']))
        elif MsgType == 'event':
            content = wechat.wxEvent()
            return HttpResponse(content)
        else:
            print(wechat.data['MsgType'])
            return HttpResponse('error')

def qrcode(request, id):
    employee = Employees.objects.get(id=id)
    if employee.qrcode == None:
        wechat = WechatAction()
        qr = wechat.get_qrcode(id)
        file_path = settings.MEDIA_ROOT + '/uploads/qrcode/' + str(id) + '.jpg'
        # 文件形式存储
        with open(file_path, 'wb') as file:
            file.write(qr)
        employee.qrcode = settings.MEDIA_URL + 'uploads/qrcode/' + str(id) + '.jpg'
        employee.save()
    return HttpResponseRedirect('/admin/member/employees/')


def profile(request):
    store = System.objects.get(name='store_name')
    code = request.GET['code']
    work = WorkWachat()
    member = work.getUserInfo(code)
    detail = work.getUserDetail(member['UserId'])
    try:
        employee = Employees.objects.get(userid=member['UserId'])
    except ObjectDoesNotExist as e:
        employee = ''
        print(e)
    return render(request, 'profile.html', {
        'employee': employee,
        'avatar': detail['avatar'],
        'store': store.content,
    })

def newProfile(request):
    config = {
        'appId': settings.WECHAT_KEY['AppId'],
        'timestamp': str(time.time()),
        'nonceStr': getRandom(12)
    }
    wechat = WechatAction()
    config['signature'] = wechat.jsapiSign(config['timestamp'], config['nonceStr'], 'http://127.0.0.1:8000/member/newProfile/')
    # 发卡信息
    card = Cards.objects.get(id=2)

    return render(request, 'new_profile.html', {
        'config': config,
    })

def payView(request):
    return render(request, 'pay.html')